import { Color, Component, Sprite, Tween, isValid, tween } from "cc";
import { EntityTypeEnum, IVec2, StateTypeEnum } from "../../Common";
import DataManager from "../../Runtime/DataManager";
import { ObjectPoolManager } from "../../Runtime/ObjectPoolManager";

export class RedXManager extends Component {

    id: number
    tw: Tween<Color>
    init(id: number, position: IVec2) {
        this.id = id
        this.node.setPosition(position.x, position.y)

        const body = this.node.getChildByName('body')
        const sp = body.getComponent(Sprite)
        sp.customMaterial = null

        this.doFlash(sp)

    }

    render(state: StateTypeEnum) {

        if (state === StateTypeEnum.dead) {
            DataManager.Ins.redXMap.delete(this.id)
            ObjectPoolManager.Ins.poolFreeNode(EntityTypeEnum.redX, this.node)
        }

    }

    doFlash(sp: Sprite) {
        const color = new Color(255, 255, 255, 0)
        sp.color = color

        this.tw?.stop()
        this.tw = tween(color)
            .repeatForever(
                tween(color)
                    .to(0.4, { r: 255, g: 255, b: 255, a: 255 }, {
                        onUpdate: () => {
                            if (isValid(this.node, true)) {
                                sp.color = color
                            } else {
                                this.tw?.stop()
                            }
                        }
                    })
                    .to(0.4, { r: 255, g: 255, b: 255, a: 0 }, {
                        onUpdate: () => {
                            if (isValid(this.node, true)) {
                                sp.color = color
                            } else {
                                this.tw?.stop()
                            }
                        }
                    })
            )
            .start()

    }

}